//
//  MainViewController.m
//  BeautyClother
//
//  Created by dllo on 15/8/21.
//  Copyright (c) 2015年 宋爽. All rights reserved.
//

#import "DKNightVersion.h"


#import "MainViewController.h"
#import "define.h"
#import "AsyncConnection.h"
#import "UIImageView+WebCache.h"
#import "ImageWithLabel.h"
#import "SuitPullLayout.h"
#import "UIButton+WebCache.h"
#import "womenDetailViewController.h"
#import "MajorViewController.h"
#import "MJRefresh.h"
#import "SaleViewController.h"
#import "SpecialSaleViewController.h"
#import "TopicDetailViewController.h"
#import "RegionViewController.h"
#import "AdDetailViewController.h"
#import "SuitCell.h"
#import "CollectionController.h"
#import "UMSocial.h"
#import "DataBase.h"
#import "ItemDataBase.h"
#import "ItemsModel.h"
#import "StudyDetailViewController.h"
#import "TopicViewController.h"
#import "ButtonCell.h"
#import "RectangleCell.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "Reachability.h"
#import "TodayCell.h"
#import "LiWuShuoCell.h"
#import "SearchBarViewController.h"
#import "AFNetworking.h"

int offset = 20;
@interface MainViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, UMSocialUIDelegate, UITextFieldDelegate>


@property (nonatomic, retain) UITableView *table;
@property (nonatomic, retain) UICollectionView *collection;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, retain) NSMutableArray *topImageArr;
@property (nonatomic, retain) NSMutableArray *topArr;
@property (nonatomic, retain) UIImageView *topImage;
@property (nonatomic, retain) UIScrollView *scroll;
@property (nonatomic, retain) UIPageControl *page;
@property (nonatomic, assign) NSInteger count;
@property (nonatomic, retain) NSMutableArray *twoArr;
@property (nonatomic, retain) NSMutableArray *threeArr;
@property (nonatomic, retain) NSMutableArray *nvshenArr;
@property (nonatomic, retain) NSMutableArray *regionArr;
@property (nonatomic, retain) NSMutableArray *adArr;
@property (nonatomic, retain) NSMutableArray *collArr;
@property (nonatomic, copy) NSString *flag;
@property (nonatomic, retain) ItemsModel *model;
@property (nonatomic, retain) UIView *dark;
@property (nonatomic, retain) NSTimer *timer;

//@property (nonatomic, retain) UIBarButtonItem *item;

@property (nonatomic, retain) SuitCell *cell;
@property (nonatomic, retain) MBProgressHUD *mb;
@property (nonatomic, assign) CGFloat offHeigt;
@property (nonatomic, assign) CGFloat offWidth;
@property (nonatomic, retain) UITextField *navigationText;



@end


@implementation MainViewController

- (void)dealloc
{
    [_cell release];
    [_mb release];
    [_navigationText release];
    [_dark release];
    [_model release];
    [_collArr release];
    [_adArr release];
    [_regionArr release];
    [_nvshenArr release];
    [_twoArr release];
    [_threeArr release];
    [_page release];
    [_topArr release];
    [_topImageArr release];
    [_topImage release];
    [_scroll release];
    [_collection release];
    [_table release];
    [_array release];
    [super dealloc];
    
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.array = [NSMutableArray array];
        self.topImageArr = [NSMutableArray array];
        self.topArr = [NSMutableArray array];
        self.twoArr = [NSMutableArray array];
        self.threeArr = [NSMutableArray array];
        self.nvshenArr = [NSMutableArray array];
        self.regionArr = [NSMutableArray array];
        self.adArr = [NSMutableArray array];
        self.collArr = [NSMutableArray array];
        self.model = [[ItemsModel alloc]init];
        self.offHeigt = [[UIScreen mainScreen]bounds].size.height / 667;
        self.offWidth = [[UIScreen mainScreen]bounds].size.width / 375;
        
    }
    return self;
}
+ (BOOL)judgeConnect
{
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    NetworkStatus sta = [reach currentReachabilityStatus];
    if (sta == NotReachable) {
        return NO;
    }else{
        return YES;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self beginConnection];
    [self createTableView];
    [self createScroll];

    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
#pragma mark -
#pragma mark - night 单例
    self.dark = [[UIView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.dark.backgroundColor = [UIColor blackColor];
    _dark.alpha = 0.7;
    _dark.userInteractionEnabled = NO;
    
    UIBarButtonItem *left = [[UIBarButtonItem alloc]init];
    [left setImage:[UIImage imageNamed:@"sousuo.png"]];

    self.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithRed:1 green:0 blue:0.5 alpha:1];

#pragma mark -
#pragma mark 加载的圈
    BOOL net = [MainViewController judgeConnect];
    if (net) {
        
    
    self.mb = [[MBProgressHUD alloc]initWithView:[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]];
    [self.view addSubview:self.mb];
        self.mb.labelText = @"努力加载着";
    [self.mb show:YES];
    }else
        
    {
       
            UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 150 * _offWidth, 60 *_offHeigt)];
            image.backgroundColor = [UIColor darkGrayColor];
            image.center = self.view.center;
            [self.view addSubview:image];
        image.layer.cornerRadius = 5;
        image.layer.masksToBounds = YES;
            [image release];
            
            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 150 * _offWidth, 60 *_offHeigt)];
            label.text = @"没有联网";
        label.textAlignment = 1;
            [image addSubview:label];
            label.textColor = [UIColor whiteColor];
            [label release];
            [UIView animateWithDuration:1.5 animations:^{
                
                image.alpha = 0.2;
                
            } completion:^(BOOL finished) {
                [image removeFromSuperview];
            }];
            
        }
    [self createNaviText];
    // Do any additional setup after loading the view.
}

- (NSTimer *)timer
{
    if (_timer == nil) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    }
    return _timer;
}



- (void)viewWillAppear:(BOOL)animated
{
    if (self.collArr.count != 0) {
        [self.collection reloadData];
    }
}

- (void)createNaviText
{
    self.navigationText = [[UITextField alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 250 *_offWidth) / 2, 0, 250*_offWidth, 30 *_offHeigt)];
    _navigationText.delegate = self;
    _navigationText.placeholder = @"🍉 搜索搭配:";
    _navigationText.borderStyle = 3;
    _navigationText.layer.borderWidth = 0.2;
    self.navigationItem.titleView = _navigationText;
   
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(SearchAction:)];
    [self.navigationText addGestureRecognizer:tap];
    _navigationText.userInteractionEnabled = YES;
    [tap release];
}

- (void)SearchAction:(UIBarButtonItem *)button
{
    SearchBarViewController *search = [[SearchBarViewController alloc] init];
    [self.navigationController pushViewController:search animated:YES];
    [search release];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    return [textField resignFirstResponder];
}


#pragma mark -
#pragma mark 上拉加载 下拉刷新

- (void)addHeader
{
//    __block MainViewController *actionVC = self;
    
    [self.table addHeaderWithCallback:^{
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"刷新");
            //            [actionVC.collection reloadData];
            [self.table headerEndRefreshing];
        });
    }];

}

- (void)addFooter
{
    __block MainViewController *actionVC = self;
    
    [self.table addFooterWithCallback:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
           
            NSDictionary *dic = @{@"limit":@"20",
                                  @"offset":[NSString stringWithFormat:@"%d", offset]};
            [AsyncConnection asyncConnection:MAIN_AD parmaters:dic block:^(NSData *data) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSMutableArray *arr = [[dic objectForKey:@"data"]objectForKey:@"items"];
                if (arr.count == 0) {
                    [self.table footerEndRefreshing];
                }else
                {
                    [self.adArr addObjectsFromArray:arr];
                    [actionVC.table reloadData];
                    offset += 20;
                }
            }path:@"main_liwushuo"];
            [self.table footerEndRefreshing];
        });
    }];
}


#pragma mark -
#pragma mark 网络请求 数据解析
- (void)beginConnection
{
    NSDictionary *dic = @{@"cid":@"1",
                          @"page":@"1",
                          @"token":@"A2C8A7F0-5A1D-4614-9F42-9455C27499CB",
                          @"ua":@"iPhone%7C1.7.11",
                          @"lang":@"en",
                          @"sig":@"b5aea3c2472b1440727161480",
                          @"nt":@"wifi"};
    
    
    
    [AsyncConnection asyncConnection:MAIN_TOP parmaters:dic block:^(NSData *data)  {
        NSDictionary *handleData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.topArr = [handleData objectForKey:@"ads"];
     
        self.count = self.topArr.count;
        if (self.topArr.count != 0) {
            
        
        [self.topImageArr addObject:[[self.topArr objectAtIndex:self.count - 1]objectForKey:@"img"]];
        for (int i = 0; i < self.count; i++) {
            [self.topImageArr addObject:[[self.topArr objectAtIndex:i]objectForKey:@"img"]];
        }
        [self.topImageArr addObject:[[self.topArr objectAtIndex:0]objectForKey:@"img"]];
        
        
        [self createScroll];
        }
        
        [self newConnection];
        
    }path:@"main_top"];
    
}

- (void)newConnection
{
//    AFHTTPRequestOperationManager *man = [[AFHTTPRequestOperationManager alloc] init];
//    [man GET:MAIN_NEW parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        
//        self.twoArr = [[responseObject objectForKey:@"data"]objectForKey:@"items"];
//        
//        [self threeConnection];
//        
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        
//    }];
    
    http://api2.hichao.com/mall/tags?gc=appstore&gf=iphone&gn=mxyc_ip&gv=6.3.3&gi=D8580E8A-8527-4EBB-B8AF-A3D8172A0099&gs=750x1334&gos=9.0.2&access_token=
    [AsyncConnection asyncConnection:MAIN_NEW parmaters:nil block:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.twoArr = [[dic objectForKey:@"data"]objectForKey:@"items"];
        
        [self threeConnection];
    }path:@"main_new"];
}

- (void)threeConnection
{
//    AFHTTPRequestOperationManager *man = [[AFHTTPRequestOperationManager alloc] init];
//    [man GET:MAIN_THREE parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        self.threeArr = [[responseObject objectForKey:@"data"]objectForKey:@"items"];
//        [self nvshenConnection];
//
//        
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        
//    }];
    [AsyncConnection asyncConnection:MAIN_THREE parmaters:nil block:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.threeArr = [[dic objectForKey:@"data"]objectForKey:@"items"];
        [self nvshenConnection];
    }path:@"main_three"];
}

- (void)nvshenConnection
{
//    AFHTTPRequestOperationManager *man = [[AFHTTPRequestOperationManager alloc] init];
//    [man GET:MAIN_WOMEN parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        self.nvshenArr = [[responseObject objectForKey:@"data"]objectForKey:@"items"];
//        [self regionConnection];
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        
//    }];
    [AsyncConnection asyncConnection:MAIN_WOMEN parmaters:nil block:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.nvshenArr = [[dic objectForKey:@"data"]objectForKey:@"items"];
        [self regionConnection];
    }path:@"main_women"];
}

- (void)regionConnection
{
//    AFHTTPRequestOperationManager *man = [[AFHTTPRequestOperationManager alloc] init];
//    [man GET:MAIN_REGION parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        self.regionArr = [[responseObject objectForKey:@"data"]objectForKey:@"items"];
//        [self adConnection];
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        
//    }];
    [AsyncConnection asyncConnection:MAIN_REGION parmaters:nil block:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.regionArr = [[dic objectForKey:@"data"]objectForKey:@"items"];
        [self adConnection];
    }path:@"main_region"];
}

- (void)adConnection
{
    NSDictionary *dic = @{@"limit":@"20",
                          @"offset":@"0"};
    
//    AFHTTPRequestOperationManager *man = [[AFHTTPRequestOperationManager alloc] init];
//    [man GET:MAIN_AD parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSMutableArray *arr = [[responseObject objectForKey:@"data"]objectForKey:@"items"];
//        [self.adArr addObjectsFromArray:arr];
//        [self collConnection];
//
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        
//    }];
    
    [AsyncConnection asyncConnection:MAIN_AD parmaters:dic block:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
       NSMutableArray *arr = [[dic objectForKey:@"data"]objectForKey:@"items"];
        [self.adArr addObjectsFromArray:arr];
        [self collConnection];
    }path:@"main_liwushuo"];
}

- (void)collConnection
{
    
    NSDictionary *dic = @{@"category":@"全部",
                          @"lts":@"",
                          @"pin":@"",
                          @"flag":@"",
                          @"gv":@"6.3.0",
                          @"gf":@"iphone"};
    [AsyncConnection asyncConnection:MAIN_COLL parmaters:dic block:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *arr = [[dic objectForKey:@"data"]objectForKey:@"items"];
        [self.collArr addObjectsFromArray:arr];
        
        [self.table reloadData];
//        [self createScroll];
        self.flag = [[dic objectForKey:@"data"]objectForKey:@"flag"];
        
        
    }path:@"main_coll"];
}


#pragma mark -
#pragma mark - 上面是三行用tableView

- (void)createTableView
{
    
    self.table = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 112) style:UITableViewStylePlain];

    [self.view addSubview:self.table];
    self.table.delegate = self;
    self.table.dataSource = self;
    
    
    [self.table release];
    [self addFooter];
    [self.mb removeFromSuperview];
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 5;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.collArr.count == 0) {
        self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
        return 0;
    }else
    {
    [self.mb removeFromSuperview];
    return 6;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 5) {
        return self.adArr.count;
    }
    if (section == 4) {
        return 2;
    }
    else{
    return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse"];
        }
        cell.backgroundColor = [UIColor clearColor];
        return cell;
    }
    if (indexPath.section == 1) {
        ButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:@"two"];
        if (cell == nil) {
            cell = [[ButtonCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"two"];
        }
        NSArray *imm = @[@"g.png", @"sun.png", @"o.png", @"snow.png", @"品牌街", @"明天穿什么", @"小美街", @"风尚志"];
        cell.backgroundColor = [UIColor clearColor];
        cell.brand.ima.image = [UIImage imageNamed:[imm objectAtIndex:0]];
        cell.brand.title.text = [imm objectAtIndex:4];
        cell.brand.tag = 100;
        
        cell.put.ima.image = [UIImage imageNamed:[imm objectAtIndex:1]];
        cell.put.title.text = [imm objectAtIndex:5];
        cell.put.tag = 200;
        
        cell.beauty.ima.image = [UIImage imageNamed:[imm objectAtIndex:2]];
        cell.beauty.title.text = [imm objectAtIndex:6];
        cell.beauty.tag = 300;

        cell.fashion.ima.image = [UIImage imageNamed:[imm objectAtIndex:3]];
        cell.fashion.title.text = [imm objectAtIndex:7];
        cell.fashion.tag = 400;
        
        UITapGestureRecognizer *brand = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(next:)];
        UITapGestureRecognizer *put = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(next:)];
        UITapGestureRecognizer *beauty = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(next:)];
        UITapGestureRecognizer *fashion = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(next:)];

        [cell.brand addGestureRecognizer:brand];
        [cell.put addGestureRecognizer:put];
        [cell.beauty addGestureRecognizer:beauty];
        [cell.fashion addGestureRecognizer:fashion];
      
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell ;
    }
    if (indexPath.section == 2) {
        RectangleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"three"];
        if (cell == nil) {
            cell = [[RectangleCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"three"];
        }
        
        [cell.image1 sd_setImageWithURL:[NSURL URLWithString:[[[self.threeArr objectAtIndex:indexPath.row]objectForKey:@"component"]objectForKey:@"picUrl"]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
        [cell.image2 sd_setImageWithURL:[NSURL URLWithString:[[[self.threeArr objectAtIndex:indexPath.row + 1]objectForKey:@"component"]objectForKey:@"picUrl"]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
        [cell.image3 sd_setImageWithURL:[NSURL URLWithString:[[[self.threeArr objectAtIndex:indexPath.row + 2]objectForKey:@"component"]objectForKey:@"picUrl"]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
        
        UITapGestureRecognizer *image1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(threeTap:)];
        UITapGestureRecognizer *image2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(threeTap:)];
        UITapGestureRecognizer *image3 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(threeTap:)];
        
        [cell.image1 addGestureRecognizer:image1];
        [cell.image2 addGestureRecognizer:image2];
        [cell.image3 addGestureRecognizer:image3];
        
        cell.image1.userInteractionEnabled = YES;
        cell.image2.userInteractionEnabled = YES;
        cell.image3.userInteractionEnabled = YES;
        
        cell.image1.tag = 10;
        cell.image2.tag = 20;
        cell.image3.tag = 30;
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        return cell ;
    }
    if (indexPath.section == 3) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"women"];
        if (cell ==  nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"women"];
        }
        UIImageView *iamge = [[UIImageView alloc]initWithFrame:CGRectMake(5, 5, self.view.frame.size.width - 10, 90 * _offHeigt)];
        [cell.contentView addSubview:iamge];
        iamge.layer.cornerRadius = 5;
        iamge.layer.masksToBounds = YES;
        [iamge sd_setImageWithURL:[NSURL URLWithString:[[[self.nvshenArr objectAtIndex:0]objectForKey:@"component"]objectForKey:@"picUrl"]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
        cell.backgroundColor = [ UIColor clearColor];
        return cell ;
    }
    if (indexPath.section == 4) {
        TodayCell *cell = [tableView dequeueReusableCellWithIdentifier:@"major"];
        if (cell == nil) {
            cell = [[TodayCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"major"];
        }
        cell.text1.text = [[[self.regionArr objectAtIndex:indexPath.row * 2] objectForKey:@"component"]objectForKey:@"title"];
        cell.text2.text = [[[self.regionArr objectAtIndex:indexPath.row * 2 + 1] objectForKey:@"component"]objectForKey:@"title"];
        NSString *tt = @"今日上新:";
        cell.today1.text = [tt stringByAppendingString:[[[[self.regionArr objectAtIndex:indexPath.row * 2]objectForKey:@"component"]objectForKey:@"action"]objectForKey:@"post_id"]];
        cell.today2.text = [tt stringByAppendingString:[[[[self.regionArr objectAtIndex:indexPath.row * 2 + 1]objectForKey:@"component"]objectForKey:@"action"]objectForKey:@"post_id"]];

        [cell.image1 sd_setImageWithURL:[NSURL URLWithString:[[[self.regionArr objectAtIndex:indexPath.row * 2]objectForKey:@"component"]objectForKey:@"picUrl"]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
        [cell.image2 sd_setImageWithURL:[NSURL URLWithString:[[[self.regionArr objectAtIndex:indexPath.row * 2 + 1]objectForKey:@"component"]objectForKey:@"picUrl"]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
       
        UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(regionDetail:)];
        
        UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(regionDetail:)];
        
        [cell.image1 addGestureRecognizer:tap1];
        [cell.image2 addGestureRecognizer:tap2];
        cell.image1.tag = indexPath.row * 2;
        cell.image2.tag = indexPath.row * 2 + 1;
        
        cell.image1.userInteractionEnabled = YES;
        cell.image2.userInteractionEnabled = YES;

        cell.backgroundColor = [UIColor clearColor];
        return cell;
    }
    if (indexPath.section == 5) {
        LiWuShuoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"aaa"];
        if (cell == nil) {
            cell = [[LiWuShuoCell alloc]initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:[NSString stringWithFormat:@"%ld, %ld", (long)indexPath.section, indexPath.row]];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell.image sd_setImageWithURL:[NSURL URLWithString:[[self.adArr objectAtIndex:indexPath.row]objectForKey:@"cover_image_url"]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
        cell.label.text = [[self.adArr objectAtIndex:indexPath.row]objectForKey:@"title"];
        cell.backgroundColor = [UIColor clearColor];
        return cell;
    }
    else{
        return [[[UITableViewCell alloc]init]autorelease];
    }
}

- (void)timerAction:(NSTimer *)timer
{
    NSInteger index = self.scroll.contentOffset.x / self.scroll.frame.size.width;
    if (index == self.topImageArr.count - 2 ) {
        _scroll.contentOffset = CGPointMake(self.scroll.frame.size.width, 0);
        _page.currentPage = 0;
    }else
    {
        _scroll.contentOffset = CGPointMake((index + 1) * self.scroll.frame.size.width, 0);
        _page.currentPage = index;
        
    }
    }


- (void)regionDetail:(UITapGestureRecognizer *)tap
{
    NSArray *arr =@[@"日韩专区", @"欧美专区", @"国内专区" , @"设计师专区"];
    RegionViewController *region = [[RegionViewController alloc]init];
    region.kid = [[[[self.regionArr objectAtIndex:tap.view.tag]objectForKey:@"component"]objectForKey:@"action"]objectForKey:@"id"];
    region.name = [arr objectAtIndex:tap.view.tag];
    region.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:region animated:YES];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 3) {
        womenDetailViewController *women = [[womenDetailViewController alloc]init];
        women.hidesBottomBarWhenPushed = YES;
        women.url = [NSURL URLWithString:@"http://api2.hichao.com/theme?gc=appstore&gf=iphone&gn=mxyc_ip&gv=6.3.0&gi=2CC19978-A0E5-49F2-9719-59DC5EDE6BBB&gs=640x1136&gos=8.4&access_token=I7OQDp90vxcyU2lFmyZBxJa2u_dbL6JfRqSfkDT127E&id=71&width=320"];
        [self.navigationController pushViewController:women animated:YES];
    }
    if (indexPath.section == 5) {
        AdDetailViewController *ad = [[AdDetailViewController alloc]init];
        ad.hidesBottomBarWhenPushed = YES;
        ad.aid = [[[self.adArr objectAtIndex:indexPath.row]objectForKey:@"id"]stringValue];
        [self.navigationController pushViewController:ad animated:YES];
    }
}

- (void)next:(UITapGestureRecognizer *)button
{
    womenDetailViewController *women = [[womenDetailViewController alloc]init];
    women.hidesBottomBarWhenPushed = YES;
    if (button.view.tag == 100) {
        women.url = [NSURL URLWithString:@"http://ichuanyi.com/index.php?method=brandstreet.show&cardId=1432889112&type=4"];
       
        [self.navigationController pushViewController:women animated:YES];
    }
    if (button.view.tag == 200) {
         women.url = [NSURL URLWithString:@"http://ichuanyi.com/suit/1372848379/1450011222"];
        [self.navigationController pushViewController:women animated:YES];
    }
    if (button.view.tag == 300) {
        women.url = [NSURL URLWithString:@"http://ichuanyi.com/index.php?method=brandstreet.show&cardId=1432889433&type=3"];
        [self.navigationController pushViewController:women animated:YES];
    }
    if (button.view.tag == 400) {
        women.url = [NSURL URLWithString:@"http://ichuanyi.com/suit/tag/%E6%AC%A7%E7%BE%8E"];
        [self.navigationController pushViewController:women animated:YES];
    }
        [women release];
}

- (void)threeTap:(UITapGestureRecognizer *)tap
{
    if (tap.view.tag == 10) {
        MajorViewController *major = [[MajorViewController alloc]init];
        major.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:major animated:YES];
    }
    if (tap.view.tag == 20) {
        SaleViewController *sale = [[SaleViewController alloc]init];
        sale.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:sale animated:YES];
    }
    if (tap.view.tag == 30) {
        SpecialSaleViewController *specail = [[SpecialSaleViewController alloc]init];
        specail.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:specail animated:YES];
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 200 * _offHeigt;
    }
    if (indexPath.section == 1 || indexPath.section == 2 || indexPath.section == 3) {
        return 100 *_offHeigt;
    }if (indexPath.section == 4) {
        return 230 *_offHeigt;
    }if (indexPath.section == 5) {
        return 150 *_offHeigt;
    }else
    {
        return 600 *_offHeigt;
    }
}

- (void)createScroll
{
    self.scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.table.frame.size.width, 200 * _offHeigt)];
    _scroll.backgroundColor = [UIColor clearColor];
    self.scroll.pagingEnabled = YES;
    self.scroll.bounces = NO;
    [self.table addSubview:self.scroll];
    self.scroll.contentSize = CGSizeMake(self.table.frame.size.width * (_count + 2), 0);
    self.scroll.delegate = self;
    self.scroll.contentOffset = CGPointMake(self.scroll.frame.size.width, 0);
    [self createImageView];
    [self.scroll release];
    [self timer];
}

- (void)createImageView
{
    if (self.topImageArr.count != 0) {
        for (int i = 0; i < self.count + 2; i++) {
            UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(i * self.scroll.frame.size.width, 0, self.scroll.frame.size.width, self.scroll.frame.size.height)];
            [self.scroll addSubview:image];
            
            [image sd_setImageWithURL:[NSURL URLWithString:[self.topImageArr objectAtIndex:i]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(lunbotu:)];
            image.tag = i ;
            if (image.tag == 0) {
                image.tag = self.count;
            }
            if (image.tag == self.count + 1) {
                image.tag = 2;
            }
            [image addGestureRecognizer:tap];
            image.userInteractionEnabled = YES;
            [image release];
        }
        self.page = [[UIPageControl alloc]initWithFrame:CGRectMake(100 * _offWidth, 150 * _offHeigt, 175 *_offWidth, 50 *_offHeigt)];
        self.page.currentPageIndicatorTintColor = [UIColor lightGrayColor];
        self.page.pageIndicatorTintColor = [UIColor whiteColor];
        self.page.numberOfPages = self.count;
        [self.table addSubview:self.page];
        [self.page release];
    }
}

- (void)lunbotu:(UITapGestureRecognizer *)tap
{
    TopicDetailViewController *topic = [[TopicDetailViewController alloc]init];
    topic.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:topic animated:YES];
    NSString *str = [[self.topArr objectAtIndex:tap.view.tag - 1]objectForKey:@"uri"];
    topic.tid = [str substringFromIndex:5];
    topic.hidesBottomBarWhenPushed = YES;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //
    //先让计时器停止
    [self.timer invalidate];
    if (scrollView == self.scroll) {
        
        _page.currentPage = scrollView.contentOffset.x / scrollView.frame.size.width - 1;
        if (scrollView.contentOffset.x < 0) {
            scrollView.contentOffset = CGPointMake(_count * scrollView.frame.size.width, 0);
            _page.currentPage = _count - 1;
        } else if (scrollView.contentOffset.x == (_count + 1) * scrollView.frame.size.width)
        {
            scrollView.contentOffset = CGPointMake(scrollView.frame.size.width, 0);
            _page.currentPage = 0;
        }
    }
    self.timer = nil;
    [self timer];
}

# if 0
#pragma mark -
#pragma mark - 下面的内容用collectionview

- (void)createCollectionView
{
    SuitPullLayout *flow = [[SuitPullLayout alloc]init];
    flow.layoutArr = self.collArr;
    flow.minimumInteritemSpacing = 20;
    flow.minimumLineSpacing = 100;
    flow.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 2020 * _offHeigt, self.view.frame.size.width, 40 *_offHeigt)];
    [self.table addSubview:label];
    label.text = @"最新搭配·每日上新";
    label.textAlignment = 1;
    [label release];
    self.collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 2060 *_offHeigt, self.view.frame.size.width, 550 *_offHeigt) collectionViewLayout:flow]
    ;


    self.collection.delegate = self;
    self.collection.dataSource = self;
    self.collection.bounces = NO;
    [self.collection registerClass:[SuitCell class] forCellWithReuseIdentifier:@"coll"];
    [self.collection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"ddd"];
    [self.collection release];
    self.collection.backgroundColor = [UIColor whiteColor];
    
    [self addFooter];
    [self addHeader];
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
//    NSLog(@"%ld", self.collArr.count);
    return self.collArr.count - 1;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *pic = [[[self.collArr objectAtIndex:indexPath.item]objectForKey:@"component"]objectForKey:@"picUrl"];
    NSArray *arr = [pic componentsSeparatedByString:@"?"];
    if ((indexPath.item % 21 - 1 == 0 && indexPath.item != 1) || indexPath.item == 0) {
        
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ddd" forIndexPath:indexPath];
        
        UIImageView *iii = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 180 *_offWidth, cell.frame.size.height)];
        
        iii.layer.cornerRadius = 5;
        iii.layer.masksToBounds = YES;
        [cell.contentView addSubview:iii];
        
        
        [iii sd_setImageWithURL:[NSURL URLWithString:[arr objectAtIndex:0]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
        cell.backgroundColor = [UIColor clearColor];
        return cell;
    }
    else
    {
    self.cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"coll" forIndexPath:indexPath];
     NSDictionary *dic = [[self.collArr objectAtIndex:indexPath.item]objectForKey:@"component"];
        
        
        
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, 180 *_offWidth, 40 *_offHeigt)];
    [self.collection addSubview:label];
        UILabel *day = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 40 *_offWidth, label.frame.size.height)];
        [label addSubview:day];
        day.text = [[[self.collArr objectAtIndex:0]objectForKey:@"component"]objectForKey:@"day"];
        day.font = [UIFont systemFontOfSize:30];
        
        UILabel *month = [[UILabel alloc]initWithFrame:CGRectMake(40 * _offWidth, 0, 40 *_offWidth, label.frame.size.height / 2)];
     
        [label addSubview:month];
        month.textColor = [UIColor lightGrayColor];
        month.text = [[[self.collArr objectAtIndex:0]objectForKey:@"component"]objectForKey:@"weekDay"];
        [month release];
        UILabel *week = [[UILabel alloc]initWithFrame:CGRectMake(40 *_offWidth, label.frame.size.height / 2, 60 *_offWidth, label.frame.size.height / 2)];
        week.textColor = [UIColor lightGrayColor];
        [label addSubview:week];
        week.text = [[@"/" stringByAppendingString:[[[self.collArr objectAtIndex:0]objectForKey:@"component"]objectForKey:@"monthOnly"]]stringByAppendingString:@"月"];
        [week release];
        
//        UILabel *quan = [[UILabel alloc]initWithFrame:CGRectMake(100 *_offWidth, 0, 80*_offWidth, label.frame.size.height / 2)];
//        [label addSubview:quan];
//        quan.textColor = [UIColor lightGrayColor];
//        quan.text = @"全球新品推荐";
//        quan.textAlignment = 2;
//        quan.font = [UIFont systemFontOfSize:12];
        
        UILabel *date = [[UILabel alloc]initWithFrame:CGRectMake(100 *_offWidth, label.frame.size.height / 2, 50 *_offWidth, label.frame.size.height / 2)];
        [label addSubview:date];
        date.textAlignment = 2;
        date.font = [UIFont systemFontOfSize:12];
        date.textColor = [UIColor colorWithRed:255/255 green:0 blue:255/255 alpha:0.5];
        date.text = [[[self.collArr objectAtIndex:0]objectForKey:@"component"]objectForKey:@"showTime"];
        [date release];
//        [quan release];
        UILabel *fabu = [[UILabel alloc]initWithFrame:CGRectMake(150 *_offWidth, label.frame.size.height / 2, 30 *_offWidth, label.frame.size.height / 2)];
        [label addSubview:fabu];
        fabu.textAlignment = 2;
        fabu.font = [UIFont systemFontOfSize:12];
        fabu.textColor = [UIColor lightGrayColor];
        fabu.text = @"发布";
    
    [label release];
    _cell.layer.cornerRadius = 5;
    _cell.layer.masksToBounds = YES;
    

        
      [_cell.image sd_setImageWithURL:[NSURL URLWithString:[arr objectAtIndex:0]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
           _cell.title.text = [dic objectForKey:@"description"];
    [_cell.share setTitle:[dic objectForKey:@"itemsCount"] forState:UIControlStateNormal];
        [_cell.share addTarget:self action:@selector(share:) forControlEvents:UIControlEventTouchUpInside];
    [_cell.like setTitle:[dic objectForKey:@"collectionCount"] forState:UIControlStateNormal];
        _cell.like.tag = indexPath.item;
        NSInteger i = [[[[self.collArr objectAtIndex:indexPath.item]objectForKey:@"component"]objectForKey:@"collectionCount"] integerValue];
        BOOL exit = [ItemDataBase selectWithid:[dic objectForKey:@"id"]];
        if (exit) {
            _cell.like.selected = YES;
            [_cell.like setImage:[UIImage imageNamed:@"sheart.png"] forState:UIControlStateNormal];
            _cell.like.tintColor = [UIColor colorWithRed:255/255 green:0 blue:255/255 alpha:0.8];
            [_cell.like setTitle:[NSString stringWithFormat:@"%ld", i + 1] forState:UIControlStateNormal];
        }else
        {
            [_cell.like setImage:[UIImage imageNamed:@"heart.png"] forState:UIControlStateNormal];
            [_cell.like setTintColor:[UIColor darkGrayColor]];
            _cell.like.selected = NO;
        }

        [_cell.like addTarget:self action:@selector(shoucang:) forControlEvents:UIControlEventTouchUpInside];
        _cell.backgroundColor = [UIColor clearColor];
    return _cell;
    }
}
#endif

#pragma mark - 
#pragma mark 分享
- (void)share:(UIButton *)bu
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"55e57550e0f55a57db000e09"
                                      shareText:_cell.title.text
                                     shareImage:_cell.image.image
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,nil]
                                       delegate:self];
}

#pragma mark - 
#pragma mark 收藏
- (void)shoucang:(UIButton *)button
{
    
    [DataBase dataBaseOpen];
    [self.model setValuesForKeysWithDictionary:[[self.collArr objectAtIndex:button.tag]objectForKey:@"component"]];
    
    if (button.selected == YES) {
        [DataBase dataBaseOpen];
        [ItemDataBase deleteWithid:self.model.iid];
        NSInteger i = [[[[self.collArr objectAtIndex:button.tag]objectForKey:@"component"]objectForKey:@"collectionCount"] integerValue];
        [button setTintColor:[UIColor darkGrayColor]];
        [button setImage:[UIImage imageNamed:@"heart.png"] forState:UIControlStateNormal];

        [button setTitle:[NSString stringWithFormat:@"%ld", i] forState:UIControlStateNormal];
        
    }
    if (button.selected == NO) {
        self.model.iid = [[[self.collArr objectAtIndex:button.tag]objectForKey:@"component"]objectForKey:@"id"];
        self.model.desc = [[[self.collArr objectAtIndex:button.tag]objectForKey:@"component"]objectForKey:@"description"];
        self.model.width = [[[self.collArr objectAtIndex:button.tag]objectForKey:@"width"]floatValue];
        self.model.height = [[[self.collArr objectAtIndex:button.tag]objectForKey:@"height"]floatValue];
        [ItemDataBase insertWithModel:self.model];
        
        [button setImage:[UIImage imageNamed:@"sheart.png"] forState:UIControlStateNormal];
        [button setTintColor:[UIColor clearColor]];
        NSInteger i = [[[[self.collArr objectAtIndex:button.tag]objectForKey:@"component"]objectForKey:@"collectionCount"] integerValue];

            i = i + 1;

        [button setTitle:[NSString stringWithFormat:@"%ld", i] forState:UIControlStateNormal];
        
    }
    if (button.selected == YES) {
        button.selected = NO;
    }else
    {
        button.selected = YES;
    }
    
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ((indexPath.item % 21 - 1 == 0 && indexPath.item != 1) || indexPath.item == 0) {
        if ([[[[[[self.collArr objectAtIndex:indexPath.item]objectForKey:@"component"]objectForKey:@"actions"]objectAtIndex:1]objectForKey:@"actionType"] isEqualToString:@"detail"]) {
            
        
        StudyDetailViewController *region = [[StudyDetailViewController alloc]init];
        region.sid = [[[[[self.collArr objectAtIndex:indexPath.item]objectForKey:@"component"]objectForKey:@"actions"]objectAtIndex:1]objectForKey:@"id"];
        [self.navigationController pushViewController:region animated:YES];
        [region release];
        }
        if ([[[[[[self.collArr objectAtIndex:indexPath.item]objectForKey:@"component"]objectForKey:@"actions"]objectAtIndex:1]objectForKey:@"actionType"] isEqualToString:@"topicDetail"])
        {
            TopicViewController *topic = [[TopicViewController alloc]init];
            topic.tid = [[[[[self.collArr objectAtIndex:indexPath.item]objectForKey:@"component"]objectForKey:@"actions"]objectAtIndex:1]objectForKey:@"id"];
            [self.navigationController pushViewController:topic animated:YES];
            [topic release];
        }
    }else
    {
    CollectionController *coll = [[CollectionController alloc]init];
    [self.navigationController pushViewController:coll animated:YES];
    coll.aid = [[[self.collArr objectAtIndex:indexPath.item]objectForKey:@"component"]objectForKey:@"showTypeId"];
    [coll release];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
